﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace CRUD
{
    public class server
    {
        public static List<Client> lst = new List<Client>();
        private HttpListener serverLi = null;
        string Prefix = null;
        public static IDS ids = null;
        public class Client
        { 
            Thread thr;
            string msg;
            public HttpListenerContext Context = null;           
            public Client(HttpListenerContext context)
            { 
                 Context = context;            
                Thread thr = new Thread(connect);
                Console.WriteLine(context.ToString());
                thr.Start();
               
            }
          
            void send()
            {
                Console.WriteLine("Server respond:  "+msg);
                HttpListenerResponse response = Context.Response;
                byte[] buffer = System.Text.Encoding.Default.GetBytes(msg);
                response.ContentLength64 = buffer.Length;
                StreamWriter streamWriter = new StreamWriter(response.OutputStream);
                streamWriter.Write(buffer);                
                streamWriter.Close();            

            }
            void action(string message)
            {
                //thr.Abort();
                string[] splited = message.Split('*');
                Console.WriteLine("recieved:  "+message);
                //   Console.WriteLine(message);
                string path = splited[2];
                ids = Factory.gi(path);
                MyList x = new MyList();
                string[] strArray = message.Split('*', ' ');
                switch (strArray[0])
                {
                    case "Cr":
                        Person p = new Person();
                        for (int i = 3; i < strArray.Length - 1; i++)
                        {
                            string[] temp = strArray[i].Split(new Char[] { ';' });
                            p.LoadFromCSV(temp);
                        }
                        ids.Create(p);
                        break;
                    case "R":
                        x.read(path);
                        msg = "";
                        foreach (Person pp in x)
                        {
                            msg += pp.SaveToSCV();
                            msg += " ";
                        }
                        send();
                        break;
                    case "Up":
                        Person a = new Person();
                        string[] tempSt = strArray[3].Split(new Char[] { ';' });
                        a.Age = Convert.ToInt32(tempSt[1]);
                        a.FName = tempSt[2];
                        a.LName = tempSt[3];
                        a.id = Convert.ToInt32(tempSt[4]);
                        ids.Update(a);
                        x.Clear();
                        x.read(path);
                        msg = "";
                        foreach (Person pp in x)
                        {
                            msg += pp.SaveToSCV();
                            msg += " ";
                        }
                        send();
                        break;

                    case "Del":
                        x.delete(path, Convert.ToInt32(strArray[3]));
                        x.Clear();
                        x.read(path);
                        msg = "";
                        foreach (Person pp in x)
                        {
                            msg += pp.SaveToSCV();
                            msg += " ";
                        }
                        send();
                        break;
                    default:
                        throw new ArgumentException();
                }
            }
            public void connect()
            {
                
                HttpListenerRequest request = Context.Request;
                Stream inputStream = request.InputStream;
                int i = (int)request.ContentLength64;
                byte[] inBuffer = new byte[i];
                inputStream.Read(inBuffer, 0, i);
                msg = Encoding.Default.GetString(inBuffer);
                request.InputStream.Flush();
                action(msg);
            }
        }
        public void Start()
        { 
            Prefix = "http://+:13000/";
            serverLi = new HttpListener();
            serverLi.Prefixes.Add(Prefix);          
            serverLi.Start();
            Console.Write("Waiting for a connection... ");
            Client cl = null;
            while (true)
            { 
                HttpListenerContext context =serverLi.GetContext();               
                cl = new Client(context);                
                lst.Add(cl);
            }             
        }
    }
}
